<?php
/**商品表视图模型
 * @Author: 976123967@qq.com
 * @Date:   2014-08-31 16:50:19
 * @Last Modified by:   chen
 * @Last Modified time: 2014-09-07 20:48:18
 */
class GoodsViewModel extends ViewModel{
	// 指定表名
	public $table='goods';



	public $view = array(
		'category'=>array(
			'type'=>INNER_JOIN,
			'on'=>'category.cid=goods.cid'
		),
		'locality'=>array(
			'type'=>INNER_JOIN,
			'on'=>'locality.lid=goods.lid'
		),
		'shop'=>array(
			'type'=>INNER_JOIN,
			'on'=>'shop.shopid=goods.shopid'
		),

		'goods_detail'=>array(
			'type'=>INNER_JOIN,
			'on'=>'goods_detail.goods_id=goods.gid'
		)
	);

	/**
	 * [get_goods_all 所有商品]
	 * @param  [type] $where [description]
	 * @param  [type] $limit [description]
	 * @return [type]        [description]
	 */
	public function get_goods_all($where=null,$limit=null)
	{

		$data = $this->join('category,locality,shop')->where($where)->limit($limit)->order('gid desc')->select();
		if(!$data) return $data;
		foreach($data as $k=>$v)
		{

			$pic = pathinfo($v['goods_img']);
			$data[$k]['list_img'] = __ROOT__.'/'.$pic['dirname'].'/'.$pic['filename'].'_310x185'.".".$pic['extension'];
		}
		return $data;

	}


	/**
	 * [get_goods_one 单条商品记录]
	 * @param  [type] $gid [description]
	 * @return [type]      [description]
	 */
	public function get_goods_one($gid)
	{
		$data = $this->find($gid);
		if(!$data) return $data;
		// 组合数组
		// 服务
		$data['goods_server'] = unserialize($data['goods_server']);

		$server = array_values($data['goods_server']);
		$serverC = C('goodsServer');
		$data['server'][] = $serverC[$server[0]];
		$data['server'][] = $serverC[$server[1]];
		
		// 折扣
		$data['discount'] = round($data['price']/$data['old_price']*10,1);

		// 图片
		$pic = pathinfo($data['goods_img']);
		$data['detail_img'] = __ROOT__.'/'.$pic['dirname'].'/'.$pic['filename'].'_460x280'.".".$pic['extension'];

		// 剩余时间
	 	$lifetime= ($data['end_time']-time())/60*60*24;
	 	if($lifetime<3)
	 	{

	 		$data['lifetime'] = '剩余<span>'.$lifetime.'</span>' ;
	 	}
	 	else
	 	{
	 		$data['lifetime'] = '结束时间：'.date('Y-m-d H:i:s',$data['end_time']);
	 	}

	 	
		return $data;
	}


	/**
	 * [set_search_where 设置筛选条件]
	 */
	public function set_search_where()
	{

		$where = array(
			'start_time'=>array('lt'=>time()),
			'end_time'=>array('gt'=>time())
		);

		// 设置筛选分类cid
		$cid = Q('get.cid',0,'intval');
		if($cid)
		{
			$sonCids = K('Category')->get_son_cagtegory_cid($cid);
			$sonCids[] = $cid;
			$where[C('DB_PREFIX').'goods.cid'] = $sonCids;
		}
		


		// 设置筛选地区lid
		$lid = Q('get.lid',0,'intval');
		if($lid)
		{
			$sonLids = K('City')->get_son_city_cid($lid);
			$sonLids[] = $lid;
			$where[C('DB_PREFIX').'goods.lid'] = $sonLids;
		}


		// 设置价格筛选
		$pid = Q('get.pid',0);
		if($pid)
		{
			$price = explode('-', $pid);
			if(isset($price[1]))
				$where[]=" price >= {$price[0]} AND price <= {$price[1]}";
			else
				$where[]=" price >= {$price[0]} ";
		}

		return $where;
	}	
}